<template>
  <div class="app-container">


    <el-row justify="space-between">
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item>
            <el-select v-model="queryParams.status" prop="status" placeholder="请选择" @select="handleQuery" style="width: 100px">
              <el-option key="" label="全部" value=""></el-option>
              <el-option key="新建" label="新建" value="新建"></el-option>
              <el-option key="执行中" label="执行中" value="执行中"></el-option>
              <el-option key="取消" label="取消" value="取消"></el-option>
              <el-option key="暂停" label="暂停" value="暂停"></el-option>
              <el-option key="已完成" label="已完成" value="已完成"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" prop="subjectName">
            <el-input
              v-model="queryParams.subjectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" >
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:subject:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:subject:export']"
            >导出</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>


    <el-table border v-loading="loading" :data="subjectList"  @selection-change="handleSelectionChange">
      <el-table-column label="项目编号" align="center" prop="subjectNo" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="dealEdit(scope.row)"
            v-hasPermi="['system:subject:edit']"
          >{{scope.row.subjectNo}}</el-button>
        </template>

      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100"/>
      <el-table-column label="项目进度" align="center" width="80">
        <template slot-scope="scope">
          {{computeRate(scope.row.taskList)}}
        </template>
      </el-table-column>
      <el-table-column label="项目状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag  type="success">{{scope.row.status}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="category" width="80"/>
      <el-table-column label="项目时间" align="center" prop="ddate" width="120"/>
      <el-table-column label="项目名称" align="left" prop="subjectName" width="220"/>
      <el-table-column label="立项时间" align="center" prop="fireDate" width="120"/>
      <el-table-column label="要求完成时间" align="center" prop="demandDate" width="120"/>
      <el-table-column label="负责人" align="center" prop="headUser" width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <el-tag effect="plain" :key="index" v-for="(item,index) in scope.row.headUsers">{{item.nickName}}</el-tag>
            <div slot="reference" class="name-wrapper">
              <el-tag v-if="scope.row.headUsers[0]" effect="plain">{{scope.row.headUsers[0].nickName}}</el-tag>
              <el-tag v-if="scope.row.headUsers[1]" effect="plain">{{scope.row.headUsers[1].nickName}}</el-tag>
              <span v-if="scope.row.headUsers.length > 2">...</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="订阅人" align="center" prop="copyUser" width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <el-tag effect="plain" :key="index" v-for="(item,index) in scope.row.copyUsers">{{item.nickName}}</el-tag>
            <div slot="reference" class="name-wrapper">
              <el-tag v-if="scope.row.copyUsers[0]" effect="plain">{{scope.row.copyUsers[0].nickName}}</el-tag>
              <el-tag v-if="scope.row.copyUsers[1]" effect="plain">{{scope.row.copyUsers[1].nickName}}</el-tag>
              <span v-if="scope.row.copyUsers.length > 2">...</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="left" prop="desp" width="280"/>
      <el-table-column label="操作" fixed="right"  align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            :disabled="canEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            disabled
            @click="updStatus(scope.row,'执行中')"
            v-if="'执行中' != scope.row.status"
            :disabled="canEdit(scope.row)"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            disabled
            @click="updStatus(scope.row,'暂停')"
            v-if="'暂停' != scope.row.status"
            :disabled="canEdit(scope.row)"
          >暂停</el-button>
          <el-button
            size="mini"
            type="text"
            disabled
            v-if="'取消' != scope.row.status"
            @click="updStatus(scope.row,'取消')"
            :disabled="canEdit(scope.row)"
          >取消</el-button>
          <el-button
            size="mini"
            type="text"
            disabled
            v-if="'已完成' != scope.row.status"
            @click="updStatus(scope.row,'已完成')"
            :disabled="canEdit(scope.row)"
          >完成</el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['system:subject:remove']"-->
          <!--          ></el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="项目名称" prop="subjectName">
              <el-input v-model="form.subjectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目时间" prop="ddate">
              <el-date-picker clearable
                              disabled
                              v-model="form.ddate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择项目时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目类型" prop="category">
              <el-select v-model="form.category">
                <el-option key="订单" label="订单" value="订单"></el-option>
                <el-option key="打样" label="打样" value="打样"></el-option>
                <el-option key="品质" label="品质" value="品质"></el-option>
                <el-option key="售后" label="售后" value="售后"></el-option>
                <el-option key="其它" label="其它" value="其它"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="desp">
          <el-input v-model="form.desp" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="立项时间" prop="fireDate">
              <el-date-picker clearable
                              v-model="form.fireDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择立项时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间" prop="demandDate">
              <el-date-picker clearable
                              v-model="form.demandDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择要求完成时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="负责人" prop="headUser">
              <el-card>
                搜索:<el-select
                v-model="form.headUserVal"
                  filterable
                  remote
                  @change="addHeadUser"
                  reserve-keyword
                  placeholder="请输入负责人"
                  :remote-method="findAllUsers"
                  :loading="loading">
                  <el-option
                    v-for="item in userList"
                    :key="item.userName"
                    :label="item.nickName"
                    :value="item.userName">
                  </el-option>
                </el-select>
                <el-divider/>
                <el-tag effect="plain"
                        :disable-transitions="false"
                        closable
                        @close="subHeadUser(index)"
                        :key="index"
                        v-for="(item,index) in form.headUsers">
                  {{item.nickName}}
                </el-tag>
              </el-card>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送人" prop="copyUser">
             <el-card>
               搜索:<el-select
                 v-model="form.copyUserVal"
                 filterable
                 remote
                 @change="addCopyUser"
                 reserve-keyword
                 placeholder="请输入抄送人"
                 :remote-method="findAllUsers"
                 :loading="loading">
                 <el-option
                   v-for="item in userList"
                   :key="item.userName"
                   :label="item.nickName"
                   :value="item.userName">
                 </el-option>
               </el-select>
               <el-divider/>
               <el-tag effect="plain"
                       closable
                       :disable-transitions="false"
                       :key="index"
                       @close="subCopyUsers(index)"
                       v-for="(item,index) in form.copyUsers">
                 {{item.nickName}}
               </el-tag>
             </el-card>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubject, getSubject, delSubject, addSubject, updateSubject } from "@/api/system/subject";
import { parseTime } from '@/utils/ruoyi'
import { listUser } from '@/api/system/user'
import getters from '@/store/getters'
import Getters from '@/store/getters'
import user from '@/store/modules/user'

export default {
  name: "Subject",
  data() {
    return {
      // 按钮loading
      yUsername:user.state.name,
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目管理表格数据
      subjectList: [],
      userList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectNo: undefined,
        ddate: undefined,
        subjectName: undefined,
        desp: undefined,
        fireDate: undefined,
        demandDate: undefined,
        status: undefined,
      },
      // 表单参数
      form: {
        headUsers: [],
        copyUsers: []
      },
      // 表单校验
      rules: {
        subjectId: [
          { required: true, message: "项目ID不能为空", trigger: "blur" }
        ],
        subjectNo: [
          { required: true, message: "项目编号不能为空", trigger: "blur" }
        ],
        ddate: [
          { required: true, message: "项目时间不能为空", trigger: "blur" }
        ],
        subjectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        desp: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        fireDate: [
          { required: true, message: "立项时间不能为空", trigger: "blur" }
        ],
        demandDate: [
          { required: true, message: "要求完成时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "项目状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {

    this.getList();
  },
  methods: {

    parseTime() {
      return parseTime
    },
    findAllUsers(val){
      const query = {
        pageNum: 1,
        pageSize: 10,
        nickName:val
      }
      listUser(query).then(response => {
        this.userList = response.rows;
      });
    },
    addHeadUser: function(e) {
      let users = this.userList.filter(item => {
        return item.userName == e
      });
      const headUsers = [...users,...this.form.headUsers]
      this.form.headUsers = headUsers;
    },
    subCopyUsers:function(e){
      const users = [...this.form.copyUsers]
      users.splice(e,1)
      this.form.copyUsers = users;
    },
    subHeadUser: function(e) {
      const users = [...this.form.headUsers]
      users.splice(e,1)
      this.form.headUsers = users;
    },
    addCopyUser: function(e) {
      let users = this.userList.filter(item => {
        return item.userName == e
      });
      const copyUsers = [...users,...this.form.copyUsers]
      this.form.copyUsers = copyUsers;
    },
    /** 查询项目管理列表 */
    getList() {
      this.loading = true;
      listSubject(this.queryParams).then(response => {
        this.subjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        subjectId: undefined,
        subjectNo: undefined,
        ddate: parseTime(new Date(), '{y}-{m}-{d}'),
        subjectName: undefined,
        desp: undefined,
        fireDate: undefined,
        demandDate: undefined,
        status: undefined,
        headUser:undefined,
        headUserVal:undefined,
        headUsers:[],
        copyUsers:[],
        copyUser:undefined,
        copyUserVal:undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        update: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.subjectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const subjectId = row.subjectId || this.ids
      getSubject(subjectId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改项目管理";
      });
    },/** 完成单据操作 */
    handleFinish(row) {
      this.loading = true;
      this.reset();
      this.form.status = "已完成"
      updateSubject(this.form).then(response => {
        this.loading = false;
        this.$modal.msgSuccess("操作成功");
        this.getList();
      }).finally(() => {
        this.buttonLoading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          let strheadUser = "";
          this.form.headUsers.forEach(item=>{
            strheadUser += item.userName+","
          })
          this.form.headUser = strheadUser
          let strCopyUser = "";
          console.log(this.form.copyUsers)
          this.form.copyUsers.forEach(item=>{
            strCopyUser += item.userName+","
          })
          this.form.copyUser = strCopyUser
          this.form.createTime = undefined;
          if (this.form.subjectId != null) {
            updateSubject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addSubject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const subjectIds = row.subjectId || this.ids;
      this.$modal.confirm('是否确认删除项目管理编号为"' + subjectIds + '"的数据项？').then(() => {
        this.loading = true;
        return delSubject(subjectIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/subject/export', {
        ...this.queryParams
      }, `subject_${new Date().getTime()}.xlsx`)
    },
    /** 编辑 */
    dealEdit: function(row) {
      const subjectId = row.subjectId;
      this.$router.push("/system/subject-edit/subject/" + subjectId);
    },
    /** 新增 */
    dealAdd: function() {
      this.$router.push("/system/subject-edit/subject/0");
    },
    handleCheckedCitiesChange:function(e){
    },
    updStatus(row,status){
      row.createTime = undefined;
      this.$modal.confirm('是否确认更改项目状态为"' + status + '"？').then(() => {
        row.status = status;
        this.loading = true;
        updateSubject(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        }).finally(() => {
          this.loading = false;
        });
      })
    },
    canEdit(obj){
      if(this.yUsername == 'admin'){
        return false;
      }
      return !(obj.createBy == this.yUsername || obj.headUser.indexOf(this.yUsername+',') > -1);
    },
    computeRate(taskList){
      const total = taskList.length
      const editing = taskList.filter(item =>item.status == '执行中').length
      const finish = taskList.filter(item =>item.status == '已完成').length
      return total+'/'+editing + '/' + finish
    }
  }
};
</script>
